﻿Public Class Alpha
  Private Declare Function AlphaBlend Lib "coredll.dll" (ByVal hdcDest As IntPtr, ByVal xDest As Integer, ByVal yDest As Integer, ByVal cxDest As Integer, ByVal cyDest As Integer, ByVal hdcSrc As IntPtr, ByVal xSrc As Integer, ByVal ySrc As Integer, ByVal cxSrc As Integer, ByVal cySrc As Integer, ByVal bf As BlendFunction) As Integer

  <Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> _
  Public Structure BlendFunction
    Dim BlendOp As Byte
    Dim BlendFlags As Byte
    Dim SourceConstantAlpha As Byte
    Dim AlphaFormat As Byte
  End Structure

  Public Enum BlendOperation As Byte
    AC_SRC_OVER = 0
  End Enum

  Public Enum BlendFlags As Byte
    Zero = 0
  End Enum

  Public Enum SourceConstantAlpha As Byte
    Transparent = &H0
    Opaque = &HFF
  End Enum

  Public Enum AlphaFormat As Byte
    AC_NONE = 0
    AC_SRC_ALPHA = 1
  End Enum



  Public Shared Sub Blend(ByVal dest As Bitmap, ByVal src As Bitmap, ByVal alpha As Byte)
    Using grDest As Graphics = Graphics.FromImage(dest)
      Using grSrc As Graphics = Graphics.FromImage(src)
        Dim hdcDest As IntPtr = grDest.GetHdc
        Dim hdcSrc As IntPtr = grSrc.GetHdc

        Dim bf As BlendFunction
        bf.AlphaFormat = AlphaFormat.AC_NONE
        bf.BlendFlags = BlendFlags.Zero
        bf.BlendOp = BlendOperation.AC_SRC_OVER
        bf.SourceConstantAlpha = alpha

        AlphaBlend(hdcDest, 0, 0, dest.Width, dest.Height, hdcSrc, 0, 0, src.Width, src.Height, bf)

        grSrc.ReleaseHdc(hdcSrc)
        grDest.ReleaseHdc(hdcDest)
      End Using
    End Using
  End Sub

End Class
